import {
	RouterMount,
	createRouter,
	runtimeQuit
} from 'uni-simple-router';

const isLogin= function(){
	const token =  uni.getStorageSync('token')
	return !!token
}

const loginToPage=async function(to, from,next){
	const status = isLogin();
	
	if(status){		// 已经登录
		next({
			name:'service',
			NAVTYPE:'replaceAll'
		});
	}else{		//未登录 直接放行到登录页面
		if(to.name!='login'){
			next({
				name:'login',
				NAVTYPE:'replace'
			});
		}else{
			next();
		}
	}
}

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,  
	APP:{
		// animation:{
		// 	animationType:'slide-in-top',
		// 	animationDuration:300
		// },
		loadingPageHook:(view)=>{
			view.hide()
		}
	},
	applet:{
		animationDuration:300
	},
	routerBeforeEach:(to, from, next) => {
		console.log('+++++routerBeforeEach++++')
		const islogin = isLogin()
		if(islogin && to.name === 'login') {
			next({
				name:'service',
				NAVTYPE:'replaceAll'
			});
		} else {
			next();
		}
		
		
	},
	routerAfterEach:(to, from) => {
	   console.log('--------routerAfterEach----')
	},
	routerErrorEach:({type,msg})=>{
		console.log({type,msg});
		if(type!==2){
			router.$lockStatus=false;
		}
		// #ifdef APP-PLUS
			if(type===3){
				runtimeQuit();
			}
		// #endif
	},
	debugger:true,
	routes: [
		...ROUTES,
		// {
		//   path: '*',
		//   redirect:(...args)=>{
		// 	  console.log(args)
		// 	  return {name:'404'}
		//   }
		// },
	]
});


let count=0;
router.beforeEach((to, from, next) => {
	count++
	
	if(to.meta.auth){
		if(count==1){
			loginToPage(to, from, next);
		} else {
			const status = isLogin();
			if(status) {
				next()
			} else {
				if(to.name!='login'){
					next({
						name:'login',
						NAVTYPE:'replace'
					});
				}
			}
		}
	} else{
		const islogin = isLogin();
		if(islogin) {
			next({
				name:'service',
				NAVTYPE:'pushTab'
			});
		} else {
			next();
		}
		
	}
	
});
router.afterEach((to, from, next) => {
	console.log('afterEach---跳转结束')
});

export {
	router,
	RouterMount
}